use std::error::Error;
use std::fs;
use std::env;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust;
safe, fast, productive.
Pick three.";

       assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, prodductive.
Pick three.
Trust me.";

        assert_eq!(vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents));
    }
}

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

// 构造函数没有 &self 参数
impl Config {
    // 'static 是 lifetime
    pub fn build(mut args: impl Iterator<Item = String>,) -> Result<Config, &'static str> {

        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("使用方法：minigrep <要搜索的字符串> <文件>"),
        };

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("使用方法：minigrep <要搜索的字符串> <文件>"),
        };

        let ignore_case = env::var("IGNORE_CASE").is_ok();


        Ok(Config {query, file_path, ignore_case})
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    // On an error, ? will return the error value from the current function
    // for the caller to handle.
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

// lifetime annotations don't change how long any of the references live. Rather,
// they describe the relationships of the lifetime of multiple referencces to 
// each other without affecting the lifetimes.
//
// Notice that we need to define an explicit lifetime 'a in the signature of 
// search and use that lifetime with the contents argument and the resut value.
// Recall in Chapter 10 that the lifetime parameters specify which argument
// lifetime liftetime is connected to the lifetime of the return value. In this
// case, we indicate that the returnd  vector should contain string slices that
// reference slices of the argument contents (rather that the argument query).
//
// In other words, we tell Rust that the data returned by the search function 
// will live as long as the data passed into the search function in the
// contents argument.
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str)  -> Vec<&'a str> {
    let query = query.to_lowercase();

    contents
        .lines()
        .filter(|line| line.to_lowercase().contains(&query))
        .collect()
}
